package com.mdd.common.util;

import javax.servlet.http.HttpServletResponse;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.io.file.FileNameUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.URLUtil;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

public class FileUploadUtils {
    private static final Logger log = LoggerFactory.getLogger(FileUploadUtils.class);

    private FileUploadUtils() {
    }

    public static File upload(MultipartFile multipartFile, String filePath, boolean isKeepOriginalFilename) {
        String originalFilename = multipartFile.getOriginalFilename();
        String extensionName = FileNameUtil.extName(originalFilename);
        String fileName;
        if (isKeepOriginalFilename) {
            fileName = String.format("%s-%s.%s",FileNameUtil.getPrefix(originalFilename), DateUtil.format(LocalDateTime.now(), "yyyyMMddHHmmssSSS"), extensionName);

        } else {
            fileName = String.format("%s.%s",IdUtil.fastSimpleUUID(), extensionName);
        }

        try {
            String pathname = filePath + fileName;
            File dest = (new File(pathname)).getCanonicalFile();
            if (!dest.getParentFile().exists() && !dest.getParentFile().mkdirs()) {
                log.error("Create upload file parent path failed.");
            }

            multipartFile.transferTo(dest);
            return dest;
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return null;
        }
    }

    public static void download(HttpServletResponse response, File file) throws IOException {
        download(response, new FileInputStream(file), file.getName());
    }

    public static void download(HttpServletResponse response, InputStream inputStream, String fileName) throws IOException {
        byte[] bytes = IoUtil.readBytes(inputStream);
        response.setCharacterEncoding(StandardCharsets.UTF_8.toString());
        response.setContentType("application/octet-stream");
        response.setContentLength(bytes.length);
        response.setHeader("Content-Disposition", "attachment; filename=" + URLUtil.encode(fileName));
        IoUtil.write(response.getOutputStream(), true, bytes);
    }

    public static void downloadExcel(HttpServletResponse response, InputStream inputStream, String fileName) throws IOException {
        try (inputStream) { // 自动关闭输入流
            byte[] bytes = IoUtil.readBytes(inputStream);
            response.setCharacterEncoding(StandardCharsets.UTF_8.toString());
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setContentLength(bytes.length);
            response.setHeader("Content-Disposition", "attachment; filename=" + URLUtil.encode(fileName));
            IoUtil.write(response.getOutputStream(), true, bytes);
        } catch (IOException e) {
            // 记录异常日志
            e.printStackTrace();

            // 设置错误响应
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            try {
                response.getWriter().write("下载失败: " + e.getMessage());
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }
}
